<template>
  <div class="erp-bill-list">
    <el-card shadow="never">
      <template #header>
        <div class="erp-bill-list__header">
          <span>{{ title }}</span>
          <div>
            <el-button type="primary" size="small" @click="onCreate">新建</el-button>
          </div>
        </div>
      </template>
      <el-form :inline="true" class="erp-bill-list__search" @submit.prevent>
        <el-form-item label="单据号">
          <el-input v-model="query.billNo" clearable />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="query.status" clearable placeholder="全部">
            <el-option
              v-for="dict in erp_bill_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="往来方">
          <el-select v-model="query.partyId" filterable remote reserve-keyword :remote-method="remoteParty" :loading="loadingParty" clearable placeholder="输入编码/名称">
            <el-option v-for="p in partyOptions" :key="p.id" :label="p.label" :value="String(p.id)" />
          </el-select>
        </el-form-item>
        <el-form-item label="仓库">
          <el-select v-model="query.warehouseId" filterable remote reserve-keyword :remote-method="remoteWarehouse" :loading="loadingWarehouse" clearable placeholder="输入编码/名称">
            <el-option v-for="w in warehouseOptions" :key="w.warehouseId" :label="`${w.warehouseCode} | ${w.warehouseName}`" :value="String(w.warehouseId)" />
          </el-select>
        </el-form-item>
        <el-form-item label="提交时间">
          <el-date-picker v-model="query.timeRange" type="datetimerange" range-separator="至" start-placeholder="开始" end-placeholder="结束" value-format="YYYY-MM-DD HH:mm:ss" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="small" @click="onSearch">查询</el-button>
          <el-button size="small" @click="onReset">重置</el-button>
        </el-form-item>
      </el-form>

      <el-table :data="list" size="small" style="width: 100%">
        <el-table-column prop="billNo" label="单据号" min-width="140" />
        <el-table-column prop="status" label="状态" min-width="100">
          <template #default="{ row }">
            <DictTag :options="erp_bill_status" :value="row.status" />
          </template>
        </el-table-column>
        <el-table-column prop="warehouseId" label="仓库ID" min-width="120" />
        <el-table-column prop="submitTime" label="提交时间" min-width="160" />
        <el-table-column label="操作" width="420">
          <template #default="{ row }">
            <el-button link type="primary" size="small" @click="onEdit(row)" :disabled="row.status==='POSTED'">编辑</el-button>
            <el-button link type="primary" size="small" @click="onDetail(row)">详情</el-button>
            <el-button link type="primary" size="small" @click="onSubmit(row)" :disabled="!(row.status==='DRAFT' || row.status==='SUBMITTED') || row.status==='POSTED'">提交</el-button>
            <el-button link type="success" size="small" @click="onApprove(row)" :disabled="row.status!=='APPROVING'">审批通过</el-button>
            <el-button link type="warning" size="small" @click="onPost(row)" :disabled="row.status!=='APPROVED'">过账</el-button>
            <el-button link type="info" size="small" @click="onViewFlow(row)">查看流程</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="erp-bill-list__pagination">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          :page-sizes="[10, 20, 50]"
          :page-size="pageSize"
          :current-page="pageNum"
          @size-change="onSizeChange"
          @current-change="onPageChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref, computed, toRefs } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { pageBills, submitBill, approveBill, postBill, getBillProcId } from '@/api/erp/bill'
import { ElMessage } from 'element-plus'
import { pageWarehouse } from '@/api/erp/warehouse'
import { pageSupplier, pageCustomer } from '@/api/erp/party'
import { useDict } from '@/utils/dict'
import DictTag from '@/components/DictTag/index.vue'

interface Props { billType?: 'PO_IN' | 'SO_OUT' }
const props = defineProps<Props>()
const router = useRouter()
const route = useRoute()

// 优先使用 props.billType，如果没有则从 route.query 获取
const billType = computed(() => {
  console.log('计算 billType，props.billType:', props.billType, 'route:', route.path, route.query)
  if (props.billType) {
    console.log('使用 props.billType:', props.billType)
    return props.billType
  }
  // 从路由 query 参数获取 billType
  const queryBillType = route.query.billType as string
  if (queryBillType === 'PO_IN' || queryBillType === 'SO_OUT') {
    console.log('使用 route.query.billType:', queryBillType)
    return queryBillType as 'PO_IN' | 'SO_OUT'
  }
  // 从路由路径判断（兜底方案）
  if (route.path.includes('so-out')) {
    console.log('从路径判断为销售出库')
    return 'SO_OUT'
  }
  if (route.path.includes('po-in')) {
    console.log('从路径判断为采购入库')
    return 'PO_IN'
  }
  // 默认返回 PO_IN，但实际上应该总是有值
  console.warn('未找到 billType，使用默认值 PO_IN')
  return 'PO_IN'
})

const title = computed(() => billType.value === 'PO_IN' ? '采购入库' : '销售出库')
const list = ref<any[]>([])
const total = ref(0)
const pageNum = ref(1)
const pageSize = ref(10)
const query = reactive<{ billNo?: string; status?: string; warehouseId?: string; partyId?: string; timeRange?: string[] | [] }>({ billNo: '', status: '', warehouseId: '', partyId: '', timeRange: [] })
const warehouseOptions = ref<any[]>([])
const loadingWarehouse = ref(false)
const partyOptions = ref<any[]>([])
const loadingParty = ref(false)

// 字典
const { erp_bill_status } = useDict('erp_bill_status')

const load = async () => {
  const res = await pageBills({
    pageNum: pageNum.value,
    pageSize: pageSize.value,
    billType: billType.value,
    billNo: query.billNo || undefined,
    status: query.status || undefined,
    warehouseId: query.warehouseId || undefined,
    partyId: query.partyId || undefined,
    startTime: Array.isArray(query.timeRange) && query.timeRange.length === 2 ? query.timeRange[0] : undefined,
    endTime: Array.isArray(query.timeRange) && query.timeRange.length === 2 ? query.timeRange[1] : undefined
  })
  list.value = res?.data?.records || []
  total.value = res?.data?.total || 0
}

const onSearch = () => { pageNum.value = 1; load() }
const onReset = () => { query.billNo = ''; query.status = ''; query.warehouseId = ''; query.partyId=''; query.timeRange = []; onSearch() }
const onSizeChange = (s: number) => { pageSize.value = s; pageNum.value = 1; load() }
const onPageChange = (p: number) => { pageNum.value = p; load() }

const onCreate = () => {
  // 使用完整的绝对路径（不带 id 参数）
  const path = billType.value === 'PO_IN' ? '/erp/po-in/edit' : '/erp/so-out/edit'
  const routeName = billType.value === 'PO_IN' ? 'ErpPoInEdit' : 'ErpSoOutEdit'
  
  console.log('=== 路由跳转调试 ===')
  console.log('billType:', billType.value)
  console.log('跳转路径:', path)
  console.log('路由名称:', routeName)
  console.log('当前路由:', router.currentRoute.value)
  
  // 获取所有路由并过滤
  const allRoutes = router.getRoutes()
  const erpRoutes = allRoutes.filter(r => r.path.includes('po-in') || r.path.includes('so-out') || r.name?.toString().includes('PoIn') || r.name?.toString().includes('SoOut'))
  console.log('所有ERP相关路由:', erpRoutes.map(r => ({ name: r.name, path: r.path, children: r.children?.length })))
  console.log('展开ERP路由详情:', JSON.parse(JSON.stringify(erpRoutes.map(r => ({ name: r.name, path: r.path, children: r.children?.map(c => ({ name: c.name, path: c.path })) })))))
  
  // 检查目标路由是否存在（包括在子路由中）
  let targetRoute = allRoutes.find(r => r.name === routeName)
  if (!targetRoute) {
    // 在子路由中查找
    for (const route of allRoutes) {
      if (route.children) {
        targetRoute = route.children.find((c: any) => c.name === routeName)
        if (targetRoute) {
          console.log('在父路由的子路由中找到:', route.path)
          break
        }
      }
    }
  }
  console.log('目标路由是否存在:', !!targetRoute)
  if (targetRoute) {
    console.log('目标路由详情:', { name: targetRoute.name, path: targetRoute.path })
  } else {
    console.warn('目标路由不存在，尝试路径跳转')
    const erpParentRoute = allRoutes.find(r => r.path === '/erp' && r.children)
    if (erpParentRoute && erpParentRoute.children) {
      console.log('ERP父路由的子路由:', erpParentRoute.children.map((c: any) => ({ name: c.name, path: c.path })))
    }
    console.log('所有包含erp的路由:', allRoutes.filter(r => r.path.includes('erp')).map(r => ({ name: r.name, path: r.path, hasChildren: !!r.children, childrenCount: r.children?.length })))
    
    // 尝试手动添加路由（如果不存在）
    if (!erpParentRoute || !erpParentRoute.children?.find((c: any) => c.path === 'po-in/edit' || c.path === 'so-out/edit')) {
      console.log('尝试手动添加编辑路由')
      try {
        const editRoute = {
          path: billType.value === 'PO_IN' ? 'po-in/edit' : 'so-out/edit',
          name: routeName,
          component: () => import('@/views/erp/bill/edit.vue'),
          props: () => ({ id: undefined, billType: billType.value }),
          meta: { title: billType.value === 'PO_IN' ? '采购入库编辑' : '销售出库编辑', hidden: true }
        }
        const editRouteWithId = {
          path: billType.value === 'PO_IN' ? 'po-in/edit/:id' : 'so-out/edit/:id',
          name: routeName + 'WithId',
          component: () => import('@/views/erp/bill/edit.vue'),
          props: (route: any) => ({ id: route.params.id as string, billType: billType.value }),
          meta: { title: billType.value === 'PO_IN' ? '采购入库编辑' : '销售出库编辑', hidden: true }
        }
        if (erpParentRoute && erpParentRoute.name) {
          router.addRoute(erpParentRoute.name as string, editRoute)
          router.addRoute(erpParentRoute.name as string, editRouteWithId)
          console.log('路由已手动添加:', editRoute.path, editRouteWithId.path)
        }
      } catch (addErr: any) {
        console.error('手动添加路由失败:', addErr)
      }
    }
    
    // 直接使用路径跳转（使用字符串路径，而不是对象）
    console.log('开始路径跳转:', path)
    // 添加延迟，确保路由添加完成
    setTimeout(() => {
      router.push(path).then(() => {
        console.log('路径跳转成功！')
      }).catch((pathErr: any) => {
        console.error('路径跳转失败:', pathErr)
        console.error('路径跳转失败详情:', {
          path,
          error: pathErr,
          message: pathErr?.message,
          stack: pathErr?.stack,
          availableRoutes: allRoutes.filter(r => r.path.includes('erp')).map(r => ({ 
            name: r.name, 
            path: r.path, 
            children: r.children?.map((c: any) => ({ name: c.name, path: c.path }))
          }))
        })
        
        // 如果路径跳转失败，尝试使用 router.resolve 看看能否解析
        try {
          const resolved = router.resolve(path)
          console.log('路由解析结果:', resolved)
          if (resolved.name) {
            console.log('尝试使用解析后的路由名称跳转')
            router.push(resolved).catch((err: any) => {
              console.error('使用解析后的路由也失败:', err)
              ElMessage.error('路由跳转失败: ' + (err?.message || '未知错误'))
            })
          } else {
            ElMessage.error('路由不存在: ' + path)
          }
        } catch (resolveErr: any) {
          console.error('路由解析失败:', resolveErr)
          ElMessage.error('路由解析失败: ' + (resolveErr?.message || '未知错误'))
        }
      })
    }, 100)
    return
  }
  
  // 先尝试命名路由
  router.push({ name: routeName }).catch((err: any) => {
    console.error('命名路由跳转失败:', err)
    // 如果命名路由失败，尝试路径跳转
    console.log('尝试路径跳转:', path)
    router.push(path).catch((pathErr: any) => {
      console.error('路径跳转也失败:', pathErr)
      ElMessage.error('路由跳转失败，请检查路由配置')
    })
  })
}
const onEdit = (row: any) => {
  router.push({ name: billType.value === 'PO_IN' ? 'ErpPoInEditWithId' : 'ErpSoOutEditWithId', params: { id: String(row.billId) } })
}

const onDetail = (row: any) => {
  // 跳转到编辑页面，添加只读参数
  router.push({ 
    name: billType.value === 'PO_IN' ? 'ErpPoInEditWithId' : 'ErpSoOutEditWithId', 
    params: { id: String(row.billId) },
    query: { readonly: 'true' }
  })
}
const onSubmit = async (row: any) => {
  await submitBill(String(row.billId)); ElMessage.success('已提交'); load()
}
const onApprove = async (row: any) => {
  await approveBill(String(row.billId)); ElMessage.success('已审批'); load()
}
const onPost = async (row: any) => {
  await postBill(String(row.billId)); ElMessage.success('已过账'); load()
}

const onViewFlow = async (row: any) => {
  ElMessage.info('功能待完成')
  // TODO: 实现查看流程功能
  // const res = await getBillProcId(String(row.billId))
  // const procId = res?.data
  // if (!procId) { ElMessage.info('暂无流程实例'); return }
  // // 前置路由已存在: /workflow/process/detail/:procInsId
  // router.push({ name: 'WorkDetail', params: { procInsId: procId } })
}

onMounted(load)

const remoteWarehouse = async (queryStr: string) => {
  loadingWarehouse.value = true
  try {
    const res = await pageWarehouse({ pageNum: 1, pageSize: 20, warehouseCode: queryStr, warehouseName: queryStr })
    warehouseOptions.value = res?.data?.records || []
  } finally {
    loadingWarehouse.value = false
  }
}

const remoteParty = async (queryStr: string) => {
  loadingParty.value = true
  try {
    if (billType.value === 'PO_IN') {
      const res = await pageSupplier({ pageNum:1, pageSize:20, code: queryStr, name: queryStr })
      partyOptions.value = (res?.data?.records||[]).map((s:any)=>({ id: s.supplierId, label: `${s.supplierCode} | ${s.supplierName}` }))
    } else {
      const res = await pageCustomer({ pageNum:1, pageSize:20, code: queryStr, name: queryStr })
      partyOptions.value = (res?.data?.records||[]).map((c:any)=>({ id: c.customerId, label: `${c.customerCode} | ${c.customerName}` }))
    }
  } finally { loadingParty.value = false }
}
</script>

<style scoped lang="scss">
.erp-bill-list {
  &__header { display: flex; align-items: center; justify-content: space-between; }
  &__pagination { margin-top: 12px; display: flex; justify-content: flex-end; }
}
</style>


